import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    loginInfo: null,
    userToken: '',
    localMasterCode: '',
    online: false,
    records: []
  },
  mutations: {
    UPDATE_LOGIN_INFO(state, info) {
      state.loginInfo = info
    },
    UPDATE_USER_TOKEN(state, token) {
      state.userToken = token
    },
    SET_LOCAL_MASTER_CODE(state, code) {
      state.localMasterCode = code
    },
    SET_ONLINE(state, online) {
      state.online = online
    },
    SET_RECORDS(state, { records = [], append = true }) {
      if (append) {
        state.records = state.records.concat(records)
      } else {
        state.records = records
      }
    },
    UPDATE_RECORD(state, record) {
      const recordIndex = state.records.findIndex(r => r.id === record.id)
      if (recordIndex !== -1) {
        state.records.splice(recordIndex, 1, record)
      }
    },
    DELETE_RECORD(state, recordId) {
      const recordIndex = state.records.findIndex(r => r.id === recordId)
      if (recordIndex !== -1) {
        state.records.splice(recordIndex, 1)
      }
    }
  },
  actions: {
    updateLoginInfo({ commit }, info = null) {
      if (!info) {
        return
      }
      commit('UPDATE_LOGIN_INFO', info)
    },
    updateUserToken({ commit }, token = '') {
      if (!token) {
        return
      }
      commit('UPDATE_USER_TOKEN', token)
    },
    setLocalMasterCode({ commit }, code) {
      commit('SET_LOCAL_MASTER_CODE', code)
    },
    setOnline({ commit }, online = false) {
      commit('SET_ONLINE', online)
    },
    setRecords({ commit }, { records = [], append = true } = {}) {
      commit('SET_RECORDS', { records, append })
    },
    updateRecord({ commit }, record) {
      commit('UPDATE_RECORD', record)
    },
    deleteRecord({ commit }, recordId) {
      commit('DELETE_RECORD', recordId)
    }
  }
})
